package common

import (
	"net/http"
	"time"

	"kingbloc.sso/user"

	"kingbloc.util/util"
)

// 找回密码
func Restore(res http.ResponseWriter, req *http.Request) {
	toEmail := req.FormValue("email")
	isok := util.RegexpEmail.MatchString(toEmail)
	if !isok {
		util.WriteJSON(res, "1")
		return
	}
	// 查找用户
	userA := new(user.User)
	userA.Email = toEmail
	userA = userA.ByEmail()
	if userA == nil {
		util.WriteJSON(res, "2")
		return
	}

	// 创建邮件
	tmpStr := userA.Mobile
	if userA.Alias != "" {
		tmpStr = userA.Alias
	}

	if sendMail(toEmail, tmpStr) != nil {
		util.WriteJSON(res, "fail")
		return
	}

	util.WriteJSON(res, "ok")
}



func sendMail(to, username string) error {
	// 获取配置
	conf = GetConfig()
	host := conf.Get("email", "serveraddr")
	user := conf.Get("email", "user")
	password := conf.Get("email", "password")
	datetime := time.Now().Format(util.TimeFormat)
	//
	randCode := util.Rand()
	serverName := conf.Get("37client", "serverName")
	url := serverName + "?t=" + randCode.Hex()
	subject := "3737.io 密码重置"
	//
	body := `
<includetail>
<table width="80%" border="0" cellspacing="0" cellpadding="0" align="center" style="background:#FF9800">
<tbody>
<tr>
<td  style="  color:#ffffff; font-size:2em;">尊敬的3737互动会员：` + username + ` <hr>
<span>您在` + datetime + `提交的找回密码，点击这里<a href=\"` + url + `\" target="_blank" style="color:#fff; font-size:1.4em;  text-decoration:underline">密码重置</a>！</span>                    </td>
</tr>
</tbody>
</table>
</includetail>
`
	err := util.SendToMail(user, password, host, to, subject, body)
	return err
}
